<template>
  <div class="products-container">
    <div class="page-header">
      <h2 class="page-title">商品管理</h2>
      <el-button type="primary" @click="handleAdd">新增商品</el-button>
    </div>
    
    <div class="search-bar">
      <el-input
        v-model="searchText"
        placeholder="搜索商品名称"
        class="search-input"
        clearable
      />
      <el-select v-model="categoryFilter" placeholder="商品分类" clearable>
        <el-option
          v-for="item in categories"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <el-select v-model="statusFilter" placeholder="状态" clearable>
        <el-option label="上架" :value="true" />
        <el-option label="下架" :value="false" />
      </el-select>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>
    
    <el-table
      :data="filteredProducts"
      style="width: 100%"
      border
      stripe
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column label="商品图片" width="120">
        <template #default="scope">
          <el-image
            :src="scope.row.imageUrl"
            :preview-src-list="[scope.row.imageUrl]"
            fit="cover"
            style="width: 50px; height: 50px"
          />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" class-name="text-left" />
      <el-table-column prop="price" label="价格">
        <template #default="scope">
          ¥{{ scope.row.price.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="category.name" label="分类" />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.status ? 'success' : 'info'">
            {{ scope.row.status ? '上架' : '下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            plain
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            plain
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
          <el-button
            :type="scope.row.status ? 'warning' : 'success'"
            size="small"
            plain
            @click="handleToggleStatus(scope.row)"
          >
            {{ scope.row.status ? '下架' : '上架' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 新增/编辑商品对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑商品' : '新增商品'"
      width="600px"
    >
      <el-form
        ref="productFormRef"
        :model="productForm"
        :rules="productRules"
        label-width="100px"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="productForm.name" />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="productForm.description"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input-number
            v-model="productForm.price"
            :precision="2"
            :step="0.1"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="productForm.categoryId" placeholder="选择分类">
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品图片" prop="imageUrl">
          <div class="image-upload-container">
            <el-upload
              class="product-image-uploader"
              action="/api/upload"
              :show-file-list="false"
              :on-success="handleImageSuccess"
              :before-upload="beforeImageUpload"
            >
              <img v-if="productForm.imageUrl" :src="productForm.imageUrl" class="product-image" />
              <div v-else class="upload-placeholder">
                <el-icon><Plus /></el-icon>
                <span>点击上传图片</span>
              </div>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="productForm.status"
            active-text="上架"
            inactive-text="下架"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/utils/api'
import { Plus } from '@element-plus/icons-vue'

// 商品列表
const products = ref([])
const loading = ref(false)

// 商品分类
const categories = ref([])

// 搜索和筛选条件
const searchText = ref('')
const categoryFilter = ref('')
const statusFilter = ref('')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitLoading = ref(false)
const productFormRef = ref(null)

// 商品表单
const productForm = reactive({
  id: null,
  name: '',
  description: '',
  price: 0,
  categoryId: null,
  imageUrl: 'https://via.placeholder.com/150',
  status: true
})

// 表单验证规则
const productRules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格必须大于等于0', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ]
}

// 过滤后的商品列表
const filteredProducts = computed(() => {
  let result = products.value
  
  // 按名称搜索
  if (searchText.value) {
    const keyword = searchText.value.toLowerCase()
    result = result.filter(product => {
      return product.name.toLowerCase().includes(keyword) || 
             (product.description && product.description.toLowerCase().includes(keyword))
    })
  }
  
  // 按分类筛选
  if (categoryFilter.value) {
    result = result.filter(product => product.categoryId === categoryFilter.value)
  }
  
  // 按状态筛选
  if (statusFilter.value !== '') {
    result = result.filter(product => product.status === statusFilter.value)
  }
  
  // 更新总数
  total.value = result.length
  
  // 分页
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  
  return result.slice(startIndex, endIndex)
})

// 获取商品列表
const fetchProducts = async () => {
  loading.value = true
  try {
    const response = await api.get('/products')
    if (response.data && response.data.status === 'success') {
      products.value = response.data.data
      total.value = products.value.length
    } else {
      ElMessage.error('获取商品列表失败: ' + (response.data?.message || '未知错误'))
      products.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败，请检查网络连接')
    products.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const response = await api.get('/categories')
    if (response.data && response.data.status === 'success') {
      categories.value = response.data.data
    } else {
      ElMessage.error('获取分类列表失败: ' + (response.data?.message || '未知错误'))
      categories.value = []
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败，请检查网络连接')
    categories.value = []
  }
}



// 搜索
const handleSearch = () => {
  currentPage.value = 1
}

// 重置搜索条件
const resetSearch = () => {
  searchText.value = ''
  categoryFilter.value = ''
  statusFilter.value = ''
  currentPage.value = 1
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

// 新增商品
const handleAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑商品
const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(productForm, row)
  dialogVisible.value = true
}

// 删除商品
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除商品"${row.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 显示加载中，避免用户重复点击
      loading.value = true;
      
      // 调用API删除商品
      const response = await api.delete(`/products/${row.id}`);
      
      // 判断响应状态
      if (response.data && response.data.status === 'success') {
        ElMessage({
          message: '删除成功',
          type: 'success',
          showClose: true,
          grouping: true
        });
        // 重新获取商品列表
        fetchProducts();
      } else {
        ElMessage({
          message: '删除失败: ' + (response.data?.message || '未知错误'),
          type: 'error',
          showClose: true,
          grouping: true
        });
      }
    } catch (error) {
      console.error('删除商品失败:', error);
      // 使用grouping属性防止重复显示
      ElMessage({
        message: '删除商品失败',
        type: 'error',
        showClose: true,
        grouping: true
      });
    } finally {
      loading.value = false;
    }
  }).catch(() => {
    // 用户取消操作，不做任何处理
  });
}

// 切换商品状态
const handleToggleStatus = async (row) => {
  try {
    // 调用API更新商品状态
    const response = await api.put(`/products/${row.id}`, {
      status: !row.status
    })
    
    if (response.data && response.data.status === 'success') {
      row.status = !row.status
      ElMessage.success(`商品已${row.status ? '上架' : '下架'}`)
    } else {
      ElMessage.error('更新状态失败: ' + (response.data?.message || '未知错误'))
    }
  } catch (error) {
    console.error('更新商品状态失败:', error)
    ElMessage.error('更新商品状态失败')
  }
}

// 重置表单
const resetForm = () => {
  if (productFormRef.value) {
    productFormRef.value.resetFields()
  }
  
  Object.assign(productForm, {
    id: null,
    name: '',
    description: '',
    price: 0,
    categoryId: null,
    imageUrl: 'https://via.placeholder.com/150',
    status: true
  })
}

// 图片上传前验证
const beforeImageUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('上传图片只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 图片上传成功
const handleImageSuccess = (response) => {
  if (response.status === 'success') {
    productForm.imageUrl = response.data.url
  } else {
    ElMessage.error('上传图片失败: ' + response.message)
  }
}

// 提交表单
const submitForm = async () => {
  if (!productFormRef.value) return
  
  productFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      
      try {
        // 找到对应的分类对象
        const category = categories.value.find(item => item.id === productForm.categoryId)
        
        // 构造保存的商品数据
        const productData = {
          ...productForm,
          price: Number(productForm.price),
          categoryId: Number(productForm.categoryId)
        }
        
        let response
        
        if (isEdit.value) {
          // 编辑商品 - 调用API
          response = await api.put(`/products/${productData.id}`, productData)
        } else {
          // 新增商品 - 调用API
          delete productData.id
          response = await api.post('/products', productData)
        }
        
        if (response.data && response.data.status === 'success') {
          ElMessage.success(isEdit.value ? '商品编辑成功' : '商品添加成功')
          dialogVisible.value = false
          // 重新获取商品列表
          fetchProducts()
        } else {
          ElMessage.error((isEdit.value ? '编辑' : '添加') + '商品失败: ' + (response.data?.message || '未知错误'))
        }
      } catch (error) {
        console.error(isEdit.value ? '编辑商品失败:' : '添加商品失败:', error)
        ElMessage.error(isEdit.value ? '编辑商品失败' : '添加商品失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 页面加载时获取数据
onMounted(() => {
  fetchProducts()
  fetchCategories()
})
</script>

<style scoped>
.products-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  margin: 0;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.image-upload-container {
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.product-image-uploader {
  width: 100%;
  height: 100%;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
}
</style> 